using System.Text;

namespace Leetcode;

public class ListNodeSerializer
{

    public string Serialize(ListNode head)
    {
        StringBuilder content = new StringBuilder();
        content.Append('[');
        var cur = head;
        while (cur != null)
        {
            content.Append(cur.val);
            content.Append(',');
            cur = cur.next;
        }
        return content.ToString().TrimEnd(',') + ']';
    }

    public ListNode Deserialize(string value)
    {
        var items = value.Trim(new char[] { '[', ']', ' ' })
        .Split(',', StringSplitOptions.RemoveEmptyEntries);
        var vals = items.Where(_ => !string.IsNullOrWhiteSpace(_)).Select(_ => int.Parse(_)).ToArray();
        if (vals.Length == 0)
        {
            return null;
        }

        var head = new ListNode(vals[0]);
        var cur = head;
        for (int i = 1; i < vals.Length; i++)
        {
            cur.next = new ListNode(vals[i]);
            cur = cur.next;
        }
        return head;
    }
}
